import pygame
import sys
from bullet import Bullet
from alien import Alien

'''事件监听'''
def check_events(ship, bullets,screen,settings):
	for event in pygame.event.get():
		if event.type == pygame.QUIT:
			sys.exit()
		elif event.type == pygame.KEYDOWN:
			check_keydown_events(event,ship,screen, bullets,settings)
		elif event.type == pygame.KEYUP:
			check_keyup_events(event,ship,screen,settings)

			


def check_keydown_events(event,ship,screen, bullets,settings):
	if event.key == pygame.K_RIGHT:
		ship.move_right = True
	elif event.key == pygame.K_LEFT:
		ship.move_left = True
	elif event.key == pygame.K_SPACE:
		settings.fire_bullet = True
		

def check_keyup_events(event,ship,screen,settings):
	if event.key == pygame.K_RIGHT:
		ship.move_right = False
	elif event.key == pygame.K_LEFT:
		ship.move_left = False
	elif event.key == pygame.K_SPACE:
		settings.fire_bullet = False


def creat_fleet(settings,screen,aliens):
	alien = Alien(screen,settings)
	alien_width = alien.rect.width
	alien_height = alien.rect.height
	print("alien_width="+str(alien_width))
	#计算每行可放多少个外星人
	space_x = settings.screen_width-2*alien_width
	nums = int(space_x/(2*alien_width))
	print("nums="+str(nums))

	#5行外星人
	for row in range(5):
		#创建一行外星人
		for alien_num in range(nums):
			al = Alien(screen,settings)
			al.rect.x = int(alien_width+2*alien_width*alien_num)
			print("al.rect.x="+str(al.rect.x))
			al.rect.y = int(row*alien_height+10)
			aliens.add(al)



'''更新屏幕'''
def update_screen(screen,ship,settings, bullets,num ,aliens):
	#设置屏幕背景颜色
	screen.fill(settings.bg_color)

	#产生子弹，长按space键每15次产生一个字段
	if settings.fire_bullet and num/15==0:
		bullet = Bullet(screen,ship,settings)
		bullets.add(bullet)

	#更新子弹
	update_bullet(bullets,aliens)
	
	#画船
	ship.move(settings)
	ship.blitme()
	#画外星人
	update_aliens(settings,aliens,screen)
	
	#屏幕可见
	pygame.display.flip()


def update_bullet(bullets,aliens):
	#print("num="+str(num))
	for bullet in bullets.sprites():
		bullet.draw_bullet()

	bullets.update()
	#删除已消失的子弹
	for bullet in bullets.copy(): 
		if bullet.rect.bottom <= 0: 
			bullets.remove(bullet) 

	# 检查是否有子弹击中了外星人
	# 如果是这样，就删除相应的子弹和外星人
	collisions = pygame.sprite.groupcollide(bullets, aliens, True, True)

def update_aliens(settings,aliens,screen):
	for alien in aliens.sprites():
		if alien.check_edge():
			settings.aliens_direct *= -1

	aliens.update()
	aliens.draw(screen)